package small.common.statistic;

import small.common.statistic.metric.ArrayMetric;
import small.common.statistic.metric.Metric;

import java.util.concurrent.atomic.LongAdder;

/**
 * @author jinzhou
 * @data 2023/4/8 10:30
 */
public class DefaultStaticNode implements StaticNode {
    /**
     * 秒统计
     */
    private final Metric rollingCounterInSecond = new ArrayMetric(2, 1000);

    /**
     * 分钟统计
     */
    private final Metric rollingCounterInMinute = new ArrayMetric(60, 60 * 1000);

    /**
     * 线程计数器
     */
    private LongAdder curThreadNum = new LongAdder();

    @Override
    public void increasePassQps(int count) {
        rollingCounterInSecond.addPass(count);
        rollingCounterInMinute.addPass(count);
    }

    @Override
    public double passQps() {
        return rollingCounterInSecond.pass() / rollingCounterInSecond.getWindowIntervalInSec();
    }

    @Override
    public double previousPassQps() {
        return this.rollingCounterInMinute.previousWindowPass();
    }

    @Override
    public void increaseExceptionQps(int count) {
        rollingCounterInSecond.addException(count);
        rollingCounterInMinute.addException(count);
    }

    @Override
    public double exceptionQps() {
        return rollingCounterInSecond.exception() / rollingCounterInSecond.getWindowIntervalInSec();
    }

    @Override
    public void increaseThreadNum() {
        curThreadNum.increment();
    }

    @Override
    public void decreaseThreadNum() {
        curThreadNum.decrement();
    }

    @Override
    public long curThreadNum() {
        return curThreadNum.sum();
    }
}
